import { useFlow } from '@/hooks/useFlow';
import type { ApiResponse } from '@/libs/apiResponse';
import { Button, Form, Toast, Upload, Spin } from '@douyinfe/semi-ui';
import { Icon } from '@iconify/react';
import { useEffect, useRef, useState } from 'react';

interface Props {
  onSubmit: (values: any) => void;
  onSuccess: () => void;
  onClose: () => void;
  editData?: any;
}

export default function FlowCreateForm({
  onSuccess,
  onClose,
  onSubmit,
  editData,
}: Props) {
  const [uploadedImageUrl, setUploadedImageUrl] = useState<string>('');
  const [aiAnalysisText, setAiAnalysisText] = useState<string>('');
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isAnalyzing, setIsAnalyzing] = useState<boolean>(false);
  const { analyseImage, createFlow } = useFlow();
  const formApiRef = useRef<any>(null);
  const [form, setForm] = useState();

  useEffect(() => {
    if (editData) {
      setForm(editData);
    }
  }, [editData]);

  const onUploadSuccess = async (responseBody: ApiResponse<any>) => {
    if (responseBody.code !== 200) {
      Toast.error('文件上传失败');
      throw new Error('文件上传失败');
    }

    setUploadedImageUrl(responseBody.data.url);
    setIsAnalyzing(true);

    try {
      Toast.info('正在进行AI分析，请稍候...');
      const text = await analyseImage(responseBody.data.url);
      const analysisResult = text || '暂无分析结果';


      setAiAnalysisText(analysisResult);

      // 更新表单中的AI分析字段
      if (formApiRef.current) {
        formApiRef.current.setValues({
          ...formApiRef.current.getValues(),
          aiAnalysisText: analysisResult,
        });
      }

      Toast.success('AI分析完成');
    } catch (error) {
      console.error('AI分析失败:', error);
      Toast.error('AI分析失败，请重试');
      setAiAnalysisText('');
    } finally {
      setIsAnalyzing(false);
    }
  };

  const onUploadError = (error: any) => {
    console.error('上传失败:', error);
    Toast.error('图片上传失败，请重试');
  };

  // 添加工艺流程的API调用

  const handleCancel = () => {
    setUploadedImageUrl('');
    setAiAnalysisText('');
    setIsAnalyzing(false);
    if (formApiRef.current) {
      formApiRef.current.reset();
    }
    onClose();
  };

  return (
    <>
      <Form
        onSubmit={(values) =>
          onSubmit({
            ...values,
            imageUrl: uploadedImageUrl,
          })
        }
        className="my-4"
        getFormApi={(formApi) => (formApiRef.current = formApi)}
      >
        {({ formState, values }) => (
          <>
            <div className="space-y-6">
              <Form.Input
                field="code"
                label={
                  <div className="flex items-center gap-2">
                    <Icon
                      icon="carbon:code"
                      className="h-4 w-4 text-blue-500"
                    />
                    <span>工艺编码</span>
                  </div>
                }
                placeholder="请输入工艺编码"
                rules={[
                  { required: true, message: '工艺编码不能为空' },
                  { min: 2, message: '工艺编码至少2个字符' },
                ]}
                className="w-full"
              />

              <Form.Input
                field="name"
                label={
                  <div className="flex items-center gap-2">
                    <Icon
                      icon="tabler:file-text"
                      className="h-4 w-4 text-green-500"
                    />
                    <span>工艺简称</span>
                  </div>
                }
                placeholder="请输入工艺简称"
                rules={[{ required: true, message: '工艺简称不能为空' }]}
                className="w-full"
              />

              <div>
                <label className="mb-2 flex items-center gap-2 text-sm font-medium">
                  <Icon icon="ph:image" className="h-4 w-4 text-purple-500" />
                  <span>工艺图</span>
                  <span className="text-red-500">*</span>
                </label>
                <Upload
                  action="/api/upload"
                  accept="image/*"
                  limit={1}
                  className="w-full"
                  name="file"
                  dragMainText="点击上传或拖拽图片到这里"
                  dragSubText="支持 JPG、PNG、GIF 格式，文件大小不超过10MB"
                  onSuccess={onUploadSuccess}
                  onError={onUploadError}
                  showUploadList={true}
                  maxSize={10 * 1024 * 1024} // 10MB
                >
                  <Button
                    icon={<Icon icon="lucide:upload" className="h-4 w-4" />}
                    theme="light"
                    disabled={isAnalyzing}
                  >
                    {isAnalyzing ? '分析中...' : '上传工艺图'}
                  </Button>
                </Upload>
                {uploadedImageUrl && (
                  <div className="mt-2 flex items-center gap-1 text-sm text-green-600">
                    <Icon icon="lucide:check-circle" className="h-4 w-4" />
                    <span>图片上传成功</span>
                  </div>
                )}
              </div>

              <div>
                <Form.TextArea
                  label={
                    <div className="mb-2 flex items-center gap-2 text-sm font-medium">
                      <Icon
                        icon="tabler:photo-ai"
                        className="h-4 w-4 text-orange-500"
                      />
                      <span>AI 分析结果</span>
                      {isAnalyzing && <Spin size="small" />}
                    </div>
                  }
                  field="aiAnalysisText"
                  placeholder={
                    isAnalyzing
                      ? 'AI正在分析工艺图，请稍候...'
                      : '请先上传工艺图进行AI分析'
                  }
                  className="w-full"
                  rows={4}
                  disabled={true}
                  value={aiAnalysisText}
                ></Form.TextArea>
                {!uploadedImageUrl && (
                  <div className="mt-1 text-xs text-gray-500">
                    上传工艺图后将自动进行AI分析
                  </div>
                )}
              </div>
            </div>

            <div className="mt-8 flex justify-end gap-3">
              <Button
                theme="borderless"
                onClick={handleCancel}
                disabled={isLoading || isAnalyzing}
              >
                取消
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={isLoading}
                disabled={isAnalyzing || !uploadedImageUrl || !aiAnalysisText}
              >
                {isLoading ? 'AI 解析工艺中...' : '确认添加'}
              </Button>
            </div>
          </>
        )}
      </Form>
    </>
  );
}
